import {createApp} from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import router from './router'
import * as ElementPlusIconsVue from '@element-plus/icons-vue';
import {ElNotification} from 'element-plus'
import App from './App.vue'

import axios from 'axios';

// createApp(App).mount('#app')
const app = createApp(App)

app.use(ElementPlus)
app.use(router)
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
}

const ajax = axios.create({
    // baseURL: 'https://mcpspace.cn/api/', // 这里设置你的基础URL
    baseURL: 'http://127.0.0.1:8000/api/', // 这里设置你的基础URL
    timeout: 60000 // 请求超时时间
});

// 拦截请求
ajax.interceptors.request.use(
    config => {
        // 在发送请求前，获取新的 token
        const username = window.localStorage.getItem('userid');
        const authorization = window.localStorage.getItem('token');
        if (username && authorization) {
            // 如果这两个字段存在，则添加到请求头
            config.headers.authorization = authorization;
            config.headers.username = username;
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

ajax.interceptors.response.use(
    response => {
        if (response.data && response.data.code === 400) {
            ElNotification({
                title: '错误提示',
                message: response.data.msg,
                type: 'error',
            })
            // 跳转至 /login
            setTimeout(window.location.href = '/login', 3000);
            // router.push({path: '/login'})
        }
        // 否则，正常返回响应数据
        return response;
    },
    error => {
        // 对响应错误做点什么
        return Promise.reject(error); // 拒绝这个promise
    }
);

app.mount('#app')
export default ajax;